package com.xiaoyun.controller;

import com.xiaoyun.pojo.Users;
import com.xiaoyun.resources.FileResource;
import com.xiaoyun.service.FastdfsService;
import com.xiaoyun.service.center.CenterUserService;
import com.xiaoyun.utils.CookieUtils;
import com.xiaoyun.utils.DateUtil;
import com.xiaoyun.utils.JsonUtils;
import com.xiaoyun.utils.XYJSONResult;
import com.xiaoyun.vo.UsersVO;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;

@RestController
@RequestMapping("fdfs")
@RequiredArgsConstructor
@Slf4j
public class CenterUserController extends BaseController {

    private final FastdfsService fastdfsService;

    private final FileResource fileResource;

    private final CenterUserService centerUserService;

    @PostMapping("uploadFace")
    public XYJSONResult uploadFace(@RequestParam String userId,
                                   MultipartFile file,
                                   HttpServletRequest request,
                                   HttpServletResponse response) throws Exception {
        String path = "";
        if (file != null) {
            String filename = file.getOriginalFilename();
            if (StringUtils.isNotBlank(filename)) {
                String[] fileNameArr = filename.split("\\.");
                String suffix = fileNameArr[fileNameArr.length - 1];

                //校验是否为图片格式
                List<String> imgSub = Arrays.asList("png", "jpg", "jpeg");
                if (!imgSub.contains(suffix) || fileNameArr.length < 2) {
                    return XYJSONResult.errorMsg("图片格式不正确");
                }
                path = fastdfsService.upload(file);
                log.info("path:{}", path);
            }
        } else {
            return XYJSONResult.errorMsg("文件不能为空");
        }
        if (StringUtils.isNotBlank(path)) {

            String finalUserFaceUrl = fileResource.getHost() + path;

            Users userResult = centerUserService.updateUserFace(userId, finalUserFaceUrl);

            // 增加token
            UsersVO usersVO = conventUsersVO(userResult);
            CookieUtils.setCookie(request, response, "user",
                    JsonUtils.objectToJson(usersVO), true);
        } else {
            return XYJSONResult.errorMsg("上传失败");
        }


        return XYJSONResult.ok();
    }
}
